<template>
  <div v-if="detailUrl['horizontal_cover']">
    <van-nav-bar title="哔哩哔哩漫画" left-arrow @click-left="onClickLeft" />
    <div class="detail-pic">
      <img :src="detailUrl['horizontal_cover']" alt="" />
      <div class="detail-title">
        <div class="name">{{ detailUrl.title }}</div>
        <div class="author">
          <span>{{ detailUrl["author_name"].join("、") }}</span>
          ·
          <span>{{ detailUrl.styles[0] }}</span>
        </div>
      </div>
    </div>
    <div class="look-comic">
      <div class="icon" @click="tips()">
        <div class="chasing" v-if="isTrue">
          <van-icon name="star-o" />
          <div class="icon-desc">追漫</div>
        </div>
        <div class="noChasing" v-else>
          <van-icon name="star" class="icon-star" />
          <div class="icon-desc">已追</div>
        </div>
      </div>
      <div class="btn" @click="
        goToReadLastCode(
          epList[0]?.id,
          epList[0]['short_title'],
          epList[0]['is_locked'],
          lastPage[lastCodeIndex]?.id,
          lastPage[lastCodeIndex]?.code,
          lastPage[lastCodeIndex]?.locked,
          nextPageId,
        )">
        看第 {{ lastCodeIndex == -1 ? epList[0]['short_title'] : lastPage }} 话
      </div>
    </div>
    <div class="comic-detail-box">
      <div class="time-info">{{ orderStatus() }}</div>
      <div class="evaluate-pointer van-multi-ellipsis--l2" v-if="isShow">
        {{ detailUrl.evaluate }}
        <van-icon name="arrow-down" class="arrow-down" @click="showAll()" />
      </div>
      <div class="evaluate-show" v-else>
        {{ detailUrl.evaluate }}
        <van-icon name="arrow-up" class="arrow-up" @click="showAll()" />
      </div>
    </div>
    <div class="all-chapters">
      <span>全部章节 ({{ detailUrl.total }})</span>
      <div class="sort" v-if="flag" @click="changeCending()">
        <span>升序</span>
        <van-icon name="ascending" />
      </div>
      <div class="sort" v-else @click="changeCending()">
        <span>降序</span>
        <van-icon name="descending" />
      </div>
    </div>
    <div class="chapters-item" v-if="isFlag">
      <div class="chapter" :class="{ active: i['short_title'] == lastPage }" v-for="i in epList.slice(0, 7)"
        :key="(i.id, i['short_title'])" @click="goToRead(i.id, i['short_title'], i['is_locked'], nextPageId)">
        {{ i["short_title"] }}
        <van-icon name="lock" class="lock" v-show="i['is_locked']" />
      </div>
      <div class="showAllChapter" @click="showAllChapter()">...</div>
    </div>
    <div class="chapters-item2" v-else>
      <div class="chapter" :class="{ active: i['short_title'] == lastPage }" v-for="i in epList"
        :key="(i.id, i['short_title'])" @click="goToRead(i.id, i['short_title'], i['is_locked'], nextPageId)">
        {{ i["short_title"] }}
        <van-icon name="lock" class="lock" v-show="i['is_locked']" />
      </div>
    </div>
    <div class="comments">
      <p class="comments-title">讨论区 ({{ commentCount | playvolume }})</p>
      <div class="comment-wrap">
        <div class="scroll">
          <div class="scroll-item" v-for="u in userData" :key="u.id">
            <div class="user-info">
              <div class="user-img">
                <img :src="u.member.avatar" alt="" />
              </div>
              <div>
                <p>{{ u.member.uname }}</p>
                <p></p>
              </div>
            </div>
            <div class="user-text van-multi-ellipsis--l3">
              {{ u.content.message }}
            </div>
          </div>
          <a class="goToApp"
            href="https://manga.bilibili.com/eden/download-jumping.html?route_target=bilicomic%3A%2F%2Fdetail%2F26470%3Fh5awaken%3Db3Blbl9hcHBfZnJvbV90eXBlPWg1XyZvcGVuX2FwcF91cmw9aHR0cHM6Ly9tYW5nYS5iaWxpYmlsaS5jb20vbS9kZXRhaWwvbWMyNjQ3MA%253D%253D">去APP讨论
            ></a>
        </div>
      </div>
    </div>
    <div class="manga-recommendation">
      <div class="section-title">猜你喜欢</div>
      <div class="manga-list">
        <div class="manga-card" v-for="m in mangaUrl" :key="m['season_id']" @click="goToManga(m)">
          <img :src="m['vertical_cover']" alt="" />
          <div class="manga-title">{{ m.title }}</div>
          <div class="manga-update" v-if="!m['is_finish']">
            更新至 {{ m["last_ord"] }} 话
          </div>
          <div class="manga-update" v-else>[完结] 共 {{ m.total }} 话</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { Toast } from "vant";

export default {
  props: ["id"],
  data() {
    return {
      detailUrl: [],
      epList: [],
      commentCount: [],
      mangaUrl: [],
      userData: [],
      locked: [],
      AllEplist: [],
      nextPageId: [],
      comicId: [],
      active: '',
      lastCodeIndex: '',
      lastPage: '',
      isTrue: true,
      isShow: true,
      flag: true,
      isFlag: true,
    };
  },
  methods: {
    onClickLeft() {
      this.$router.go(-1);
    },
    async getDetailUrl() {
      let { data } = await this.$http(
        "https://apis.netstart.cn/mbcomic/ComicDetail?comic_id=" + this.id
      );
      this.detailUrl = data.data;
      this.epList = data.data["ep_list"].reverse();
      console.log(this.epList);
      // console.log(this.epList[0]['short_title']);

      for (let e = 0; e < this.epList.length; e++) {
        this.AllEplist.push(this.epList[e].id);

        if (this.epList[e]['short_title'] == this.lastPage) {

          // console.log(this.epList[e]['short_title'])

          this.active = this.epList[e]['short_title']
          console.log('active', this.active);
        }
      }

      localStorage.setItem(this.id, this.AllEplist.join('|'))

      this.comicId = this.id
    },
    async getCommentsUrl() {
      let { data } = await this.$http(
        "https://apis.netstart.cn/mbcomic/reply?oid=" + this.id
      );
      this.commentsUrl = data.data;
      this.commentCount = data.data.page.acount;
      this.userData = data.data.replies.slice(0, 6);
    },
    async getMangaUrl() {
      let { data } = await this.$http(
        "https://apis.netstart.cn/mbcomic/Recommend?comic_id=" + this.id
      );
      this.mangaUrl = data.data;
    },
    orderStatus() {
      if (this.detailUrl["is_finish"]) {
        return `已完结`;
      } else {
        return `连载中`;
      }
    },
    tips() {

      this.isCollect = JSON.parse(localStorage.getItem('collect')) || []
      let collect = {
        id: this.comicId,
        isTrue: this.isTrue
      }
      this.isCollect = [collect, ...this.isCollect.filter((c) => c.id !== collect.id)]
      localStorage.setItem('collect', JSON.stringify(this.isCollect))


      if (this.isTrue) {
        Toast("追漫成功~");
        this.isTrue = false;

      } else {
        Toast("取消追漫成功~");
        this.isTrue = true;
      }
    },

    showAll() {
      if (this.isShow) {
        this.isShow = false;
      } else {
        this.isShow = true;
      }
    },
    changeCending() {
      if (this.flag) {
        this.epList = this.epList.reverse();
        this.flag = false;
      } else {
        this.epList = this.epList.reverse();
        this.flag = true;
      }
    },
    showAllChapter() {
      if (this.isFlag) {
        this.isFlag = false;
      } else {
        this.isFlag = true;
      }
    },
    goToManga(m) {
      this.season_id = m["season_id"];
      this.$router.push({ path: "/comic_id=" + this.season_id });
    },
    goToRead(id, code, locked) {
      this.ifLastTime = JSON.parse(localStorage.getItem('code')) || []
      let lastCode = {
        id: id,
        code: code,
        locked: locked,
        comic_id: this.comicId
      }
      this.ifLastTime = [lastCode, ...this.ifLastTime.filter((l) => l.comic_id !== lastCode.comic_id)]
      localStorage.setItem('code', JSON.stringify(this.ifLastTime))

      for (let e = 0; e < this.epList.length; e++) {
        if (this.AllEplist[e] == id) {
          this.nextPageIndex = e;
        }
      }

      this.nextPageId = this.AllEplist[this.nextPageIndex + 1];

      this.$router.push(`manga/${id}/${code}?name=${this.detailUrl.title}&count=${code}&locked=${locked}&abc=${this.id}&qwe=${id}`);
    },
    goToReadLastCode(id, code, locked) {
      for (let e = 0; e < this.epList.length; e++) {
        if (this.AllEplist[e] == id) {
          this.index = e;
        }
      }
      this.nextPageId = this.AllEplist[this.index + 1];

      if (this.lastCodeIndex == -1) {
        this.$router.push(
          `manga/${id}/${code}?name=${this.detailUrl.title}&count=${code}&locked=${locked}`
        );
      } else {
        this.$router.push(
          `manga/${this.lastCode[this.lastCodeIndex].id}/${this.lastCode[this.lastCodeIndex].code}?name=${this.detailUrl.title}&count=${this.lastCode[this.lastCodeIndex].code}&locked=${this.lastCode[this.lastCodeIndex].locked}&abc=${this.id}&qwe=${this.lastCode[this.lastCodeIndex].id}`)
      }
    }
  },
  filters: {
    playvolume(arg) {
      if (arg.toString().length > 4) {
        const volume = arg / 10000;
        const realVal = parseFloat(volume).toFixed(2);
        return realVal + "w";
      } else {
        return arg;
      }
    },
  },
  computed: {
  },
  mounted() {
    this.getDetailUrl();
    this.getCommentsUrl();
    this.getMangaUrl();
    Toast.loading({
      message: "加载中...",
      duration: 1000,
    });

    this.lastCode = JSON.parse(localStorage.getItem('code'));

    this.lastCodeIndex = this.lastCode.findIndex(c => c.comic_id == this.id)

    if (this.lastCodeIndex == -1) {
      return
    }

    this.lastPage = this.lastCode[this.lastCodeIndex].code

    console.log('lastPage', this.lastPage);


    this.isCollect = JSON.parse(localStorage.getItem('collect'))

    let index = this.isCollect.findIndex(t => t.id == this.id)

    if (index == -1) {
      return
    }

    this.isTrue = !this.isCollect[index].isTrue

  },
  watch: {
    id(newid, oldid) {
      if (newid != oldid) {
        this.getDetailUrl();
        this.getCommentsUrl();
        this.getMangaUrl();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.van-nav-bar {
  width: 100%;
  position: sticky;
  top: 0;
  background-color: #fff;
  border-bottom: 1px solid #ddd;
}

.detail-pic {
  width: 375px;
  height: 210px;
  position: relative;
  margin: 0 auto;

  img {
    width: 100%;
  }

  .detail-title {
    position: absolute;
    width: 351px;
    bottom: 5px;
    padding: 0 12px;
    color: #fff;
    text-shadow: 0 1px 2px rgb(0 0 0 / 50%);
    position: absolute;
    bottom: 5px;

    .name {
      width: 351px;
      height: 20px;
      margin-bottom: 8px;
      font-size: 20px;
      line-height: 20px;
    }

    .author {
      width: 351px;
      // height: 19px;
      font-size: 12px;
      color: hsla(0, 0%, 100%, 0.9);
      line-height: 16px;
    }
  }
}

.look-comic {
  width: 343px;
  height: 44px;
  margin: 16px auto 0;
  display: flex;
  justify-content: space-between;

  .icon {
    width: 74px;
    height: 32px;
    padding: 6px 6px 6px 0;
    font-size: 32px;
    display: flex;

    .chasing {
      display: flex;
    }

    .noChasing {
      display: flex;
    }

    .icon-star {
      color: rgb(255, 211, 89);
    }

    .icon-desc {
      font-size: 18px;
      line-height: 35px;
    }
  }

  .btn {
    width: 198px;
    height: 42px;
    padding: 1px 6px;
    background-color: #fb7299;
    color: #fff;
    border-radius: 25px;
    font-size: 14px;
    text-align: center;
    line-height: 44px;
  }
}

.comic-detail-box {
  padding-top: 16px;

  .time-info {
    width: 343px;
    height: 21px;
    margin: 0 auto 8px;
  }

  .evaluate-pointer {
    width: 343px;
    height: 34px;
    margin: 0 auto 15px;
    font-size: 12px;
    color: #999;
    position: relative;
  }

  .arrow-down {
    position: absolute;
    bottom: 0;
    right: 0;
  }

  .evaluate-show {
    width: 343px;
    margin: 0 auto 15px;
    font-size: 12px;
    color: #999;
    position: relative;
  }
}

.all-chapters {
  width: 343px;
  height: 21px;
  margin: 23px auto 8px;
  display: flex;
  justify-content: space-between;

  span {
    font-size: 16px;
    color: #212121;
  }

  .sort {
    font-size: 15px;
    color: #505050;
    line-height: 21px;
  }
}

.chapters-item {
  width: 343px;
  overflow: hidden;
  margin: 0 auto;
  display: flex;
  flex-wrap: wrap;

  .chapter {
    width: 77px;
    height: 38px;
    border: 1px solid #ccc;
    border-radius: 3px;
    text-align: center;
    font-size: 14px;
    line-height: 40px;
    margin: 3px;
    position: relative;

    &.active {
      border: 1px solid #fb7299;
      background-color: #fb7299;
    }

    .lock {
      position: absolute;
      top: 0;
      right: 0;
      color: rgb(249, 160, 24);
    }
  }

  .showAllChapter {
    width: 77px;
    height: 38px;
    border: 1px solid #ccc;
    border-radius: 3px;
    text-align: center;
    font-size: 14px;
    line-height: 40px;
    margin: 3px;
  }
}

.chapters-item2 {
  width: 343px;
  margin: 0 auto;
  display: flex;
  flex-wrap: wrap;

  .chapter {
    width: 77px;
    height: 38px;
    border: 1px solid #ccc;
    border-radius: 3px;
    text-align: center;
    font-size: 14px;
    line-height: 40px;
    margin: 3px;
    position: relative;

    &.active {
      border: 1px solid #fb7299;
      background-color: #fb7299;
    }

    .lock {
      position: absolute;
      top: 0;
      right: 0;
      color: rgb(249, 160, 24);
    }
  }
}

.comments {
  width: 375px;
  margin: 0 auto;

  .comments-title {
    margin: 16px auto;
    width: 343px;
    height: 21px;
  }

  .comment-wrap {
    width: 343px;
    height: 123px;
    margin: 0 auto 16px;
    overflow-x: auto;

    .scroll {
      width: 1730px;
      height: 123px;
      overflow: scroll;
      overflow-x: auto;
      display: flex;

      .scroll-item {
        width: 225px;
        height: 93px;
        padding: 11px;
        margin-right: 12px;
        display: inline-block;
        border: 1px solid #eee;
      }

      .user-info {
        width: 100%;
        height: 35px;
        display: flex;

        .user-img {
          width: 32px;
          height: 32px;
          margin-right: 6px;

          img {
            width: 100%;
            border-radius: 50%;
          }
        }

        p {
          height: 16px;
          font-size: 12px;
          margin: 0;
        }
      }

      .user-text {
        width: 213px;
        height: 48px;
        margin-top: 10px;
        padding-right: 12px;
        margin-right: 12px;
        font-size: 12px;
      }

      .goToApp {
        width: 158px;
        height: 118px;
        background-color: #f5f7f8;
        color: #fb7299;
        text-align: center;
        line-height: 118px;
        font-size: 14px;
      }
    }
  }
}

.manga-recommendation {
  width: 343px;
  height: 420px;
  margin: 16px;
  margin: 0 auto 80px;

  .section-title {
    font-size: 16px;
    color: #212121;
    height: 40px;
    line-height: 40px;
  }

  .manga-list {
    display: flex;
    flex-wrap: wrap;

    .manga-card {
      width: 98px;
      height: 174px;
      padding: 8px;

      img {
        width: 100%;
        display: block;
      }

      .manga-title {
        width: 98px;
        height: 19px;
        margin-top: 8px;
        font-size: 14px;
        color: #222222;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }

      .manga-update {
        font-size: 12px;
        color: #999;
      }
    }
  }
}
</style>